<template>
  <!--- 操作点检详情 -->
  <view>
    <uni-forms ref="form" :rules="rules" labelPosition="top" class="form-task-content" labelWidth="120px">
      <view class="grid-body mt-30" v-for="(item, index) in formSubmit.listData" :key="index">
        <view class="check grid-common">
          <view class="flex text"
            >内容分类：
            <text>{{ item.libraryName || '--' }}</text>
          </view>
          <view class="flex text"
            >数据录入：
            <text>{{ item.inputModeDesc || '--' }}</text>
          </view>
          <view class="flex"
            ><view class="text">巡检内容：</view>
            <text class="flex-1 text">{{ item.inspectionContent || '--' }}</text>
          </view>
          <uni-forms-item name="observedValue" class="mt-20" label="观测值:">
            <view class="flex">
              <textarea
                class="text-area"
                v-model="item.observedValue"
                :style="item.inputMode == 2 || item.inputMode == 3 ? 'width: calc(100% - 200rpx)' : ''"
                maxlength="50"
                @focus="handleFocus()"
              />
            </view>
          </uni-forms-item>

          <uni-forms-item label="上传照片（最多3张）" class="mt-20" labelWidth="150">
            <image-upload state="edit" :imageUrl="item.photos || ''" @change="imageOnChange($event, item)">
            </image-upload>
          </uni-forms-item>

          <uni-forms-item name="conclusion" class="mt-20" label="结论:">
            <view class="flex">
              <CuRadioGroup
                v-model="item.conclusion"
                :list="dictData"
                :props="{ value: 'dictValue', label: 'dictLabel' }"
                @change="opinionChange($event, item)"
            /></view>
          </uni-forms-item>
        </view>
      </view>
    </uni-forms>
    <view class="submit-group">
      <!-- <button class="u-button" :ripple="true" @click="submit">正常</button> -->
      <button type="primary" class="u-button" :ripple="true" @click="saveForm">保存巡检数据</button>
      <button class="u-button-cancel mx-20" :ripple="true" @click="navigateBack()">取消</button>
    </view>
  </view>
  <!-- <view><empty></empty></view> -->
</template>

<script>
import Empty from '@/components/cu-empty/index.vue'
import { getDicts } from '@/api/system/dict.js'
import CuRadioGroup from '@/components/cu-radio-group/cu-radio-group.vue'
import ImageUpload from '@/components/image-upload/index.vue'
import { queryPositionDetail, savePositionDetail } from '@/api/equipment/Inspection-new'
// 获取 module
export default {
  name: 'executetTask',
  components: {
    Empty,
    CuRadioGroup,
    ImageUpload
  },
  data() {
    return {
      samTemp: false,
      formSubmit: {
        listData: []
      },
      type: '',
      subTaskPositionId: '', //部位id
      subTaskId: '', //子任务id
      positionName: '',
      deviceId: '',
      installationLocation: '', //设备安装位置
      dictData: [],
      rules: {
        observedValue: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        },
        conclusion: {
          rules: [
            {
              required: true,
              errorMessage: '必填项不能为空'
            }
          ]
        }
      }
    }
  },
  mounted() {
    this.getDicts()
  },
  onLoad({ subTaskPositionId, positionName, deviceId }) {
    this.deviceId = deviceId
    this.subTaskPositionId = subTaskPositionId
    this.positionName = positionName
    uni.setNavigationBarTitle({
      title: this.positionName
    })
    this.getDetail()
  },
  onPullDownRefresh() {
    this.getDetail()
  },
  beforeDestroy() {

  },
  methods: {
    imageOnChange(urlList, item) {
      item.photos = urlList.join(',')
    },
    getDicts() {
      getDicts('dfm_inspection_conclusion').then((res) => {
        this.dictData = res.data
      })
    },
    async getDetail() {
      queryPositionDetail({
        subTaskPositionId: this.subTaskPositionId
      }).then((res) => {
        this.formSubmit.listData = res.data
      })
    },

    /** * 初始化蓝牙成功 * @param {*} options  */

    openBluetoothAdapter() {
      const error = {
        10000: '未初始化蓝牙适配器',
        10001: '当前蓝牙适配器不可用，请检查蓝牙是否开启',
        10002: '没有找到指定设备',
        10003: '蓝牙连接失败'
      }
      return new Promise((resolve, reject) => {
        uni.openBluetoothAdapter({
          success: (e) => {
            console.log('初始化蓝牙成功')
            resolve()
          },
          fail: (err) => {
            reject({ code: err.code, msg: error[err.code] })
            if (err.code === 10001) {
              uni.showModal({
                title: '提示',
                content: '请打开蓝牙功能',
                success(res) {}
              })
            } else {
              showToast(error[err.code])
            }
          }
        })
      })
    },
    /**检查是否打开GPS功能（android）**/
    checkOpenGPSServiceByAndroid(options) {
      let system = uni.getSystemInfoSync()
      // 获取系统信息
      return new Promise((resolve, reject) => {
        if (system.platform === 'android') {
          // 判断平台
          var context = plus.android.importClass('android.content.Context')
          var locationManager = plus.android.importClass('android.location.LocationManager')
          var main = plus.android.runtimeMainActivity()
          var mainSvr = main.getSystemService(context.LOCATION_SERVICE)
          if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
            uni.showModal({
              title: '提示',
              content: '请打开定位服务功能',
              success(res) {}
            })
            reject({ msg: '请在设置中开启系统位置服务' })
          } else {
            resolve()
          }
        }
      })
    },
    handleClickMode(item) {

    },
    execute(item) {

    },
    handleFocus() {
      //停止测温
      if (this.samTemp) {
        this.stopSampleTemp()
      }
    },
    stopSampleTemp() {

    },
    sampleTemp(item) {

    },
    sampleVib(item) {

    },
    opinionChange(value, item) {
      if (value.dictValue == '2') {
        //上报隐患
        uni.navigateTo({
          url:
            '/pages/work/inspectTask/components/report?inspectionContent=' +
            item.inspectionContent +
            '&deviceId=' +
            this.deviceId +
            '&spareParts=' +
            this.positionName
        })
      } else if (value.dictValue == '3') {
        //上报缺陷
        uni.navigateTo({
          url: '/pages/work/inspectTask/components/reportDefects'
        })
      }
    },

    saveForm() {
      let listData = this.formSubmit.listData
      let isInput = false
      for (let i = 0; i < listData.length; i++) {
        if (listData[i].observedValue && listData[i].conclusion) {
          isInput = true
        }
      }
      if (!isInput) {
        return uni.showModal({
          content: '至少填入一项观测值和结论',
          showCancel: false
        })
      }
      savePositionDetail(this.formSubmit.listData).then(() => {
        this.$modal.msgSuccess('保存成功')
        this.navigateBack()
      })
    },
    navigateBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-task-content {
  margin-bottom: 107px;
}
.check {
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: 700;
  }

  .icon-style {
    width: 52rpx;
    height: 52rpx;
    margin-right: 20rpx;
  }

  .text {
    color: #999;
  }

  .flex-text {
    padding-top: 24rpx;
    display: flex;
    color: #999;

    text {
      color: #333;
      display: inline-block;
    }
  }

  .bor-top {
    padding-top: 20rpx;
    border-top: 1px solid #d5d7e3;
  }
}

.text-area {
  background: #f5f5f5;
  color: #333;
  border-radius: 10rpx;
  width: 100%;
  padding: 20rpx;
  height: 220rpx;
  font-size: 30rpx;
}

:deep(.uni-forms-item__label) {
  color: #999;
}
.submit-group {
  background: #fff;
  padding: 20px;
}
</style>
